#include "datareader.h"

DataReader::~DataReader()
{
    //if(ds != nullptr)delete ds;
}

DataReader::DataReader(const QByteArray &data)
{
    ds = QSharedPointer<QDataStream>(new QDataStream(data));
}

DataReader &DataReader::setData(const QByteArray &data)
{
    //if(ds != nullptr)delete ds;
    ds = QSharedPointer<QDataStream>(new QDataStream(data));
    return *this;
}

DataReader &DataReader::readLong(qint64 &data)
{
    *ds>>data;
    return *this;
}

DataReader &DataReader::readInt(int &data)
{
    *ds>>data;
    return *this;
}

DataReader &DataReader::readShort(short &data)
{
    *ds>>data;
    return *this;
}

DataReader &DataReader::readByte(qint8 &data)
{
    *ds>>data;
    return *this;
}

DataReader &DataReader::readDouble(double &data)
{
    *ds>>data;
    return *this;
}

DataReader &DataReader::readFloat(float &data)
{
    *ds>>data;
    return *this;
}

DataReader &DataReader::readBytes(QByteArray &data, LengthType lengthType, int lengthOffset)
{
    //length=true=1 (int)
    //length=false=0 (short)
    //length=2 (byte)
    int length;
    switch (lengthType) {
        case LengthType::SHORT:{short s_length;readShort(s_length);length = s_length;}break;
        case LengthType::INT:{int s_length;readInt(s_length);length = s_length;}break;
        case LengthType::BYTE:{qint8 s_length;readByte(s_length);length = s_length;}break;
        default:abort();//fuck you for your input data
    }
    length += lengthOffset;
    readRaw(data,length);
    return *this;
}

DataReader &DataReader::readRaw(QByteArray &data, int length)
{
    data += ds->device()->read(length);
    return *this;
}

DataReader &DataReader::readAll(QByteArray &data)
{
    data += ds->device()->readAll();
    return *this;
}

uint DataReader::getUnReadSize()
{
    return ds->device()->size() - ds->device()->pos();
}

DataReader &DataReader::skipBytes(int length)
{
    ds->skipRawData(length);
    return *this;
}
/*
DataReader &DataReader::readTLVS(QMap<short, QVariant> &data)
{
    while(getUnReadSize() > 0){
        short key;
        QByteArray body;
        readShort(key);
        readBytes(body,false);
        data[key] = body;
    }//readTLV
    return *this;
}
*/
DataReader &DataReader::readTLVS(QMap<short, QByteArray> &data)
{
    while(getUnReadSize() > 0){
        short key;
        readShort(key);
        readBytes(data[key],LengthType::SHORT);
    }//readTLV
    return *this;
}

